// 通过修改样式，实现点击去注册和去登陆后的界面显示变化

const registerA = document.querySelector('.register-a'); // 去登录的链接
const loginA = document.querySelector('.login-a');       // 去注册的链接
const registerDiv = document.querySelector('.register'); // 注册界面
const loginDiv = document.querySelector('.login');       // 登录界面
// 获取注册页form元素
const formRegister = document.querySelector('.register form'); // 注册页form表单
const formLogin = document.querySelector('.login form');       // 登录页form表单

// 去注册
loginA.addEventListener('click', () => {
    loginDiv.style.display = 'none';
    registerDiv.style.display = 'block';

})

// 去登录
registerA.addEventListener('click', () => {
    registerDiv.style.display = 'none';
    loginDiv.style.display = 'block';
})

// 注册页
formRegister.addEventListener('submit', async e => {
    e.preventDefault();

    // const formData = new FormData(formRegister);
    // console.log(formData);
    // console.log(typeof formData);
    // console.log(...formData);

    const username = formRegister.querySelector('input[name=username]').value.trim();
    const password = formRegister.querySelector('input[name=password]').value.trim();

    if (!username || !password) {
        return
    }

    const result = await axios({
        url: '/api/register',
        method: 'post',
        data: {
            username,
            password
        }
    });

    console.log(result);

    if (result.data.code === 0) {
        toastr.success(result.data.message, "恭喜");
        NProgress.start(); // 显示加载效果

        setTimeout(() => {
            NProgress.done(); // 终止加载效果
            registerA.click();
            loginDiv.querySelector('input[name=username]').value = username;
        }, 1500)

        formRegister.reset();
    }

})

// 登录页
formLogin.addEventListener('submit', async e => {
    e.preventDefault();

    const username = formLogin.querySelector('input[name=username]').value.trim();
    const password = formLogin.querySelector('input[name=password]').value.trim();

    if (!username || !password) {
        return
    }

    const result = await axios({
        url: '/api/login',
        method: 'post',
        data: {
            username,
            password
        }
    });

    console.log(result);

    if (result.data.code === 0) {
        toastr.success(result.data.message, "恭喜");
        NProgress.start(); // 显示加载效果
        localStorage.setItem('tokenwa',result.data.token)

        setTimeout(() => {
            NProgress.done(); // 终止加载效果
            location.href = './index.html';
        },3000)
    }

})

